package org.mspring.mlog.scheduler;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 *
 * @author Gao Youbo
 * @since 2013-1-8
 */
@Service
public class SchedulerServiceImpl implements SchedulerService {

    private static final Logger log = LoggerFactory.getLogger(SchedulerServiceImpl.class);

    @Autowired
    @Qualifier("quartzScheduler")
    private Scheduler scheduler;

    @Override
    public void schedule(String jobName, Class jobClass, long repeatInterval) {
        String triggerName = jobName + "Tigger";
        try {
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, Scheduler.DEFAULT_GROUP).build();

            SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity(triggerName, Scheduler.DEFAULT_GROUP).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(repeatInterval).repeatForever()).forJob(jobDetail).build();

            if (scheduler.getTrigger(TriggerKey.triggerKey(triggerName, Scheduler.DEFAULT_GROUP)) == null) {
                scheduler.scheduleJob(jobDetail, simpleTrigger);
            }
            scheduler.rescheduleJob(TriggerKey.triggerKey(triggerName, Scheduler.DEFAULT_GROUP), simpleTrigger);
        } catch (Exception e) {
            // 如果调度失败那么将JOB从scheduler中移除
            deleteJob(jobName);
            log.error("register job [name = " + jobName + ", class = " + jobClass + "] failure.");
        }
    }

    @Override
    public void schedule(String jobName, Class jobClass, String cronExpression) {

        String triggerName = jobName + "Tigger";
        try {
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, Scheduler.DEFAULT_GROUP).build();

            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerName, Scheduler.DEFAULT_GROUP).withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).forJob(jobDetail).build();

            if (scheduler.getTrigger(TriggerKey.triggerKey(triggerName, Scheduler.DEFAULT_GROUP)) == null) {
                scheduler.scheduleJob(jobDetail, cronTrigger);
            }
            scheduler.rescheduleJob(TriggerKey.triggerKey(triggerName, Scheduler.DEFAULT_GROUP), cronTrigger);
        } catch (Exception e) {
            // 如果调度失败那么将JOB从scheduler中移除
            deleteJob(jobName);
            log.error("register job [name = " + jobName + ", class = " + jobClass + ", cron = " + cronExpression + "] failure." + e.getMessage());
        }
    }

    @Override
    public void deleteJob(String jobName) {

        try {
            scheduler.deleteJob(JobKey.jobKey(jobName, Scheduler.DEFAULT_GROUP));
        } catch (SchedulerException e) {
            log.error("delete job [name = " + jobName + "] failure.");
        }
    }

    @Override
    public void triggerJob(String jobName) {
        try {
            scheduler.triggerJob(JobKey.jobKey(jobName, Scheduler.DEFAULT_GROUP));
        } catch (SchedulerException e) {
            log.error("trigger job [name = " + jobName + "] failure.");
        }
    }

    @Override
    public void clearJobs() {

        try {
            scheduler.clear();
        } catch (SchedulerException e) {
            log.error(e.getMessage(), e);
        }
    }

}
